﻿$(document).ready(function () {

    $("#CategoryId").change(function (e) {
        location.href = "http://" + location.host + '/SendEmail/Index?categoryId=' + $("#CategoryId").val();
    });

});
//$(function () {
//    pageGrids.EmailAddressGrid.onRowSelect(function (e) {
//        alert(e.row.EmailAddress);
//    });
//});

function selectRow(sender, ema) {
    if ($("#EmailAddress").val().indexOf(ema) < 1) {
        $("#EmailAddress").val($("#EmailAddress").val() + "," + ema);
        $(sender).html("عدم انتخاب");
    } else {
        $("#EmailAddress").val($("#EmailAddress").val().replace("," + ema, ""));
        $(sender).html(" انتخاب");
    }
}

function onChange(arg) {
    var selected = $.map(this.select(), function (item) {
        return $($(item).find("td")[0]).text();
    });

    $("#EmailAddress").val(selected.join(", "));
}

function selectAllRow() {
    var grid = $('#EmailAddressGrid').data('kendoGrid');
    //grid.tbody.children('tr').addClass('k-state-selected');
    grid.select(grid.tbody.find(">tr"));
}

function checkAll(ele) {
    var state = $(ele).is(':checked');
    var grid = $('#EmailAddressGrid').data('kendoGrid');
    $.each(grid.dataSource.view(), function () {
        if (this['IsSelected'] != state)
            this.dirty = true;
        this['IsSelected'] = state;
    });
    grid.refresh();
}

function GetSelectedItems() {

    $("#EmailAddressGrid  tbody").find('tr').each(
    function () {
        var id = $(this).find('#EmailAddressGrid').val();
        var isAdd = $(this).hasClass('k-state-selected');
        if (isAdd == true) {
            // This item is selected
            console.log($($(this).find("td")[1]).html());
        }
    });
}

function sendAutoMail() {
    var smtpServerId = $("#SmtpServerId").val();
    var smtpCredentialId = $("#SmtpCredentialId").val();
    var emailAddress = $("#EmailAddress").val();
    var subject = $("#Subject").val();
    var body = $("#Body").html();
    sendEmail(smtpServerId, smtpCredentialId, emailAddress, subject, body);
}

function sendEmail(smtpServerId, smtpCredentialId, emailAddress, subject, body) {
    var model = {
        "SmtpServerId": smtpServerId,
        "SmtpCredentialId": smtpCredentialId,
        "EmailAddress": emailAddress,
        "Subject": subject,
        "Body": body
    }

    $.ajax({
        url: 'SendEmail/Send',
        type: "POST",
        data: model,
        success: function (result) {
            alert("عملیات پایان یافت");
            $("#dAlert").html(result);
        },
        error: function (message) {
            alert("خطا رخ داد");
            $("#dAlert").html(message);
        }
    });
}

